#include "Logger.h"
#include <string>
#include <thread>
#include <ctime>
#include <iostream>

Logger &Logger::GetInstance() 
{
    static Logger instance;
    return instance;
}

#include "Logger.h"
#include <string>
#include <thread>
#include <ctime>
#include <fstream>

void Logger::Log(LogLevel log_level, const std::string &message)
{
    std::string log_level_str = log_level == INFO ? "INFO" : "ERROR";
    std::string log_message = "[" + log_level_str + "]: " + message;
    m_safe_queue.Push(log_message);

    // 用snprintf记录打印日志的文件:函数:行数信息
    // char log_line_info[1024] = {0};
    // snprintf(log_line_info, 1024, "%s:%s:%d ==> %s", __FILE__, __FUNCTION__, __LINE__, log_message.c_str());
    // std::cout << __FILE__ << ":" << __FUNCTION__ << ":" << __LINE__ << " ==> " << log_message << std::endl;
}

Logger::Logger() 
{
    // 创建一个线程，从m_safe_queue中取出日志并写入文件
    std::thread log_thread = std::thread([this]()
    {
        while(true)
        {
            std::string log_message = m_safe_queue.Pop();
            
            // 获取当前时间
            time_t now = time(nullptr);
            tm *t = localtime(&now);
            std::string filename = std::to_string(t->tm_year + 1900) + 
                                   "-" + std::to_string(t->tm_mon + 1) + 
                                   "-" + std::to_string(t->tm_mday) + ".log";

            // 以追加模式打开文件
            // 文件不存在则创建
            std::ofstream file(filename, std::ios::app);
            if(!file.is_open())
            {
                std::cout << "open file " << filename << " failed" << std::endl;
                // 结束进程
                exit(EXIT_FAILURE);
            }

            // 写入日志
            file << t->tm_hour << ":" << t->tm_min << ":" << t->tm_sec << " ==> " << log_message << std::endl;

            // 关闭文件
            if(file.is_open())
                file.close();
        } 
    });

    // 线程和log_thread变量分离
    log_thread.detach();
}